//
//  MainViewController.m
//  SaveMoney
//
//  Created by Jose Sánchez Martínez on 11/11/11.
//  Copyright (c) 2011 Mubiquo. All rights reserved.
//

#import "MainViewController.h"
#import "CustomCell.h"

@interface MainViewController(Private)
- (void) setDesiredAggregateValue;
- (void) setCurrentAggregateValue:(int)aggregate;
- (void) setCurrentMonthlyValue:(int)current;
@end

@implementation MainViewController

#define init_y 30
#define axis_y 320
#define max_pixeles 230
#define height_month 130


NSArray *aggregateArray;
NSArray *currentArray;

NSArray *monthsName;
NSArray *monthsSave;

NSArray *movementsName;
NSArray *movementsValue;

int globalGoal;
int monthlyGoal;
int numberOfMonths;
int numberOfWeeks; 
float ratioGlobal;
float ratioMonthly;
NSString *user;
NSDate *endDate;


BOOL balance = YES;


//fake
int currentWeek = 0;

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.

    [self.view addSubview:infoUserView];
    
    tableView.layer.cornerRadius = 4;
    
    UISwipeGestureRecognizer *oneFingerSwipeRight = 
    [[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(oneFingerSwipeRight:)] autorelease];
    [oneFingerSwipeRight setDirection:UISwipeGestureRecognizerDirectionRight];
    [[self view] addGestureRecognizer:oneFingerSwipeRight];
    
    UISwipeGestureRecognizer *oneFingerSwipeLeft = 
    [[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(oneFingerSwipeLeft:)] autorelease];
    [oneFingerSwipeLeft setDirection:UISwipeGestureRecognizerDirectionLeft];
    [[self view] addGestureRecognizer:oneFingerSwipeLeft];
    
    
    
    UITapGestureRecognizer *oneFingerTwoTaps = 
    [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(oneFingerTwoTaps)] autorelease];
    
    // Set required taps and number of touches
    [oneFingerTwoTaps setNumberOfTapsRequired:2];
    [oneFingerTwoTaps setNumberOfTouchesRequired:1];
    
    // Add the gesture to the view
    [detailView addGestureRecognizer:oneFingerTwoTaps];
    /*
     1 - 700
     2 - 450
     3 - 650
     4 - 250
     5 - 600
     6 - 800
     
     */

    monthsName = [[NSArray arrayWithObjects:@"Gener", @"Febrer", @"Març", @"Abril", @"Maig", nil] retain];
    
    monthsSave = [[NSArray arrayWithObjects:@"700 €", @"450 €", @"650 €", @"250 €", @"600 €", nil] retain];
    
    
    movementsName = [[NSArray arrayWithObjects:@"Nòmina", @"Aigua", @"LLum", @"Teléfon", @"Cotxe", nil] retain];
    movementsValue = [[NSArray arrayWithObjects:@"+1600 €", @"-33.45 €", @"-63.50 €", @"-45.50 €", @"-324 €", nil] retain];
    
    aggregateArray = [[NSArray arrayWithObjects:[NSNumber numberWithInt:0], [NSNumber numberWithInt:0],[NSNumber numberWithInt:0],[NSNumber numberWithInt:0], [NSNumber numberWithInt:700],
        [NSNumber numberWithInt:700], [NSNumber numberWithInt:700], [NSNumber numberWithInt:700], [NSNumber numberWithInt:1150], [NSNumber numberWithInt:1150], [NSNumber numberWithInt:1150],                       [NSNumber numberWithInt:1150], [NSNumber numberWithInt:1800], [NSNumber numberWithInt:1800], [NSNumber numberWithInt:1800], [NSNumber numberWithInt:1800], [NSNumber numberWithInt:2050], [NSNumber numberWithInt:2050], [NSNumber numberWithInt:2050], [NSNumber numberWithInt:2050], [NSNumber numberWithInt:2650], [NSNumber numberWithInt:2650], [NSNumber numberWithInt:2650], [NSNumber numberWithInt:2650], [NSNumber numberWithInt:3450], [NSNumber numberWithInt:3450], [NSNumber numberWithInt:3450], [NSNumber numberWithInt:3450], nil] retain];
    
    currentArray = [[NSArray arrayWithObjects:[NSNumber numberWithInt:1600],[NSNumber numberWithInt:1000], [NSNumber numberWithInt:900], [NSNumber numberWithInt:700], [NSNumber        numberWithInt:1600], [NSNumber numberWithInt:800], [NSNumber numberWithInt:500], [NSNumber numberWithInt:450], [NSNumber numberWithInt:1600], [NSNumber numberWithInt:1100], [NSNumber numberWithInt:800], [NSNumber numberWithInt:650], [NSNumber numberWithInt:1600], [NSNumber numberWithInt:1000], [NSNumber numberWithInt:400], [NSNumber numberWithInt:250], [NSNumber numberWithInt:1600], [NSNumber numberWithInt:1200], [NSNumber numberWithInt:650], [NSNumber numberWithInt:600],[NSNumber numberWithInt:1600], [NSNumber numberWithInt:1200], [NSNumber numberWithInt:1000], [NSNumber numberWithInt:800], [NSNumber numberWithInt:800], nil] retain];
    
    
    //fake 
    globalGoal = 3000;
    numberOfWeeks = 24;
    numberOfMonths = 6;
    monthlyGoal = globalGoal/numberOfMonths;
    desiredMonthlyLabel.text = [NSString stringWithFormat:@"%i €", monthlyGoal];
    ratioGlobal = (float)max_pixeles/(float)globalGoal;
    ratioMonthly = (float)height_month/(float)monthlyGoal;
    
    [self setDesiredAggregateValue];
    [self setCurrentMonthlyValue:[[currentArray objectAtIndex:currentWeek] integerValue]];
    [self setCurrentAggregateValue:[[aggregateArray objectAtIndex:currentWeek] integerValue]];

}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;

    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([defaults objectForKey:@"user"]) {
        user = [defaults objectForKey:@"user"];
    }
    else {
        //lanzar vista de login
        
    }
    
    if ([defaults integerForKey:@"goal"] != 0) {
        globalGoal = [defaults integerForKey:@"goal"];
        numberOfMonths = [defaults integerForKey:@"months"];
        endDate = [NSDate dateWithTimeIntervalSince1970:[defaults doubleForKey:@"enddate"]];
        monthlyGoal = globalGoal/numberOfMonths;
        
        ratioGlobal = max_pixeles/globalGoal;
    }
    
    else {
        //[self showInfo:nil];
    } 
}

- (void)oneFingerTwoTaps
{
    NSLog(@"Action: One finger, two taps");
    
    [UIView animateWithDuration:0.3 
                          delay:0
                        options:UIViewAnimationOptionAllowUserInteraction
                     animations:^{
                         detailView.alpha = 0.0;
                     }
                     completion:^(BOOL wrwg) {
                         [detailView removeFromSuperview];
                     }];
}

- (void)oneFingerSwipeLeft:(UISwipeGestureRecognizer *)recognizer 
{ 
    CGPoint point = [recognizer locationInView:[self view]];
    NSLog(@"Swipe left - start location: %f,%f", point.x, point.y);
    
    
    if (currentWeek < numberOfWeeks) {
        currentWeek ++;
    }
    
    [UIView animateWithDuration:0.3 
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         [self setDesiredAggregateValue];
                         [self setCurrentMonthlyValue:[[currentArray objectAtIndex:currentWeek] integerValue]];
                         [self setCurrentAggregateValue:[[aggregateArray objectAtIndex:currentWeek] integerValue]];
                     }
                     completion:nil];    
    
    
}


- (void)oneFingerSwipeRight:(UISwipeGestureRecognizer *)recognizer 
{ 
    CGPoint point = [recognizer locationInView:[self view]];
    NSLog(@"Swipe right - start location: %f,%f", point.x, point.y);
    
    if (currentWeek > 0) {
        currentWeek --;
    }
    
    [UIView animateWithDuration:0.3 
                          delay:0
                        options:UIViewAnimationOptionAllowUserInteraction
                     animations:^{
                         [self setDesiredAggregateValue];
                         [self setCurrentMonthlyValue:[[currentArray objectAtIndex:currentWeek] integerValue]];
                         [self setCurrentAggregateValue:[[aggregateArray objectAtIndex:currentWeek] integerValue]];
                     }
                     completion:nil];
    
    
}



- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void) setDesiredAggregateValue {
    CGRect rect =  desiredAggregate.frame;
    
    int aggregate = (globalGoal/numberOfMonths)*((floor((float)currentWeek/4.0)));
    
    int height = ratioGlobal*aggregate;
    if (height > max_pixeles) {
        height = max_pixeles;
    }
    
    rect.origin.y = axis_y - height;
    rect.size.height = height;

    
    desiredAggregate.frame = rect;
    
    desiredAggregateLabel.text = [NSString stringWithFormat:@"%i€", aggregate];
    
    rect = desiredAggregateLabel.frame;
    rect.origin.y = desiredAggregate.frame.origin.y - 20;
    desiredAggregateLabel.frame = rect;
}

- (void) setCurrentAggregateValue:(int)aggregate {
    
    CGRect rect =  currentAggregate.frame;
    
    int height = ratioGlobal*aggregate;
    if (height > max_pixeles) {
        height = max_pixeles;
    }
    
    rect.origin.y = axis_y - height;
    rect.size.height = height;
    
    currentAggregate.frame = rect;
    
    currentAggregateLabel.text = [NSString stringWithFormat:@"%i€", aggregate];
    
    rect = currentAggregateLabel.frame;
    rect.origin.y = currentAggregate.frame.origin.y - 20;
    currentAggregateLabel.frame = rect;
}

- (void) setCurrentMonthlyValue:(int)current {
    CGRect rect =  currentMonthly.frame;
    
    int height = ratioMonthly*current;
    if (height > max_pixeles) {
        height = max_pixeles;
    }
    
    rect.origin.y = axis_y - height;
    rect.size.height = height;
    
    currentMonthly.frame = rect;    
    
    
    currentMonthlyLabel.text = [NSString stringWithFormat:@"%i€", current];
    rect = currentMonthlyLabel.frame;
    rect.origin.y = currentMonthly.frame.origin.y - 20;
    currentMonthlyLabel.frame = rect;
    
}


#pragma mark DELEGATES


#pragma mark UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}


#pragma mark UITableView Delegate

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return 5;
}


//views for cells and headers
- (UITableViewCell *) tableView:(UITableView *)atableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
	UITableViewCell *cell = [atableView dequeueReusableCellWithIdentifier:CellIdentifier];
	
	if (cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
        cell = tableCell;
    }
    if (balance) {
        [(CustomCell *)cell configureWithName:[monthsName objectAtIndex:indexPath.row] value:[monthsSave objectAtIndex:indexPath.row] row:indexPath.row];
        [((CustomCell *)cell).value setTextColor:[UIColor greenColor]];
    }
    else {
        [(CustomCell *)cell configureWithName:[movementsName objectAtIndex:indexPath.row] value:[movementsValue objectAtIndex:indexPath.row] row:indexPath.row];
        if (indexPath.row == 0) {
            [((CustomCell *)cell).value setTextColor:[UIColor greenColor]];
        }
        else {
            [((CustomCell *)cell).value setTextColor:[UIColor redColor]];
        }
    }
	//cell.boton.tag = indexPath.row;
    
	
	return cell;
}




#pragma mark - Flipside View

- (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller
{
    [self dismissModalViewControllerAnimated:YES];
}

- (IBAction)showInfo:(id)sender
{    
    FlipsideViewController *controller = [[[FlipsideViewController alloc] initWithNibName:@"FlipsideViewController" bundle:nil] autorelease];
    controller.delegate = self;
    controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentModalViewController:controller animated:YES];
}

- (IBAction)showBalance:(id)sender {
    balance = YES;
    detailView.alpha = 0.0;
    [self.view addSubview:detailView];
    [tableView reloadData];
    [UIView animateWithDuration:0.3 
                          delay:0
                        options:UIViewAnimationOptionAllowUserInteraction
                     animations:^{
                         detailView.alpha = 0.8;
                     }
                     completion:nil];
    
}
- (IBAction)showExpenses:(id)sender {
    balance = NO;
    detailView.alpha = 0.0;
    [self.view addSubview:detailView];
    [tableView reloadData];
    [UIView animateWithDuration:0.3 
                          delay:0
                        options:UIViewAnimationOptionAllowUserInteraction
                     animations:^{
                         detailView.alpha = 0.8;
                     }
                     completion:nil];
}

- (IBAction)doLogin:(id)sender {
    [UIView animateWithDuration:0.3 
                          delay:0
                        options:UIViewAnimationOptionAllowUserInteraction
                     animations:^{
                         infoUserView.alpha = 0.0;
                     }
                     completion:^(BOOL wrwg) {
                         [infoUserView removeFromSuperview];
                     }];
}


@end
